package com.maiko.usercenter.aop;

import com.maiko.usercenter.annotation.AuthCheck;
import com.maiko.usercenter.common.ErrorCode;
import com.maiko.usercenter.exception.BusinessException;
import com.maiko.usercenter.model.enums.UserRoleEnum;
import com.maiko.usercenter.model.vo.LoginUserVO;
import com.maiko.usercenter.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 权限校验切面
 * 用于拦截标注了@AuthCheck注解的方法，进行权限验证
 *
 * @author: Maiko7
 * @create: 2025-07-15 9:33
 */
@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;

    /**
     * 权限校验拦截器
     * 在标注了@AuthCheck注解的方法执行前，检查用户是否具有所需权限
     *
     * @param joinPoint 切入点对象，用于获取方法签名等信息
     * @param authCheck 权限校验注解，包含需要校验的权限信息
     * @return 执行结果
     * @throws Throwable 可能抛出的异常
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        // 获取方法上指定的角色权限
        String mustRole = authCheck.mustRole();
        // 获取当前请求的RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        // 从RequestAttributes中获取HttpServletRequest对象
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

        // 获取当前登录的用户信息
        LoginUserVO loginUser = userService.getLoginUser(request);
        // 如果方法上指定了需要的角色权限
        if (StringUtils.isNotBlank(mustRole)) {
            // 根据角色权限值获取对应的枚举类型
            UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
            // 如果角色权限不存在，抛出无权限异常
            if (mustRoleEnum == null) {
                throw new BusinessException(ErrorCode.USER_NOT_AUTH);
            }
            // 获取用户的角色权限
            String userRole = loginUser.getRole();
            // 如果被封号，直接拒绝
            if (UserRoleEnum.BAN.equals(mustRoleEnum)) {
                throw new BusinessException(ErrorCode.USER_NOT_AUTH);
            }

            // 必须有管理员权限
            if (UserRoleEnum.ADMIN.equals(mustRoleEnum)) {
                // 如果用户角色不是管理员，抛出无权限异常
                if (!mustRole.equals(userRole)) {
                    throw new BusinessException(ErrorCode.USER_NOT_AUTH);
                }
            }
        }
        // 通过权限校验，放行
        return joinPoint.proceed();
    }
}